package review.thread;

/**
 * @author haomin
 * @date 2022/11/04 21:06
 **/
public class BlockQueue {
    private int[] arr;
    private int frontInd;
    private int rearInd;
    private int size;

    public BlockQueue(int capacity){
        arr = new int[capacity];
        frontInd = 0;
        rearInd = 0;
        size = 0;
    }

    public synchronized void put(int val) throws InterruptedException {
        while(size == arr.length){
            wait();
        }
        arr[rearInd] = val;
        rearInd ++; size++;
        if(rearInd == arr.length) rearInd = 0;

        notify();
    }

    public synchronized int take() throws InterruptedException {
        while (size == 0){
            wait();
        }
        int val = arr[frontInd];
        frontInd ++;
        if(frontInd == arr.length) frontInd = 0;

        notify();
        return val;
    }
}